package com.juzipi.demo.service;

import com.juzipi.demo.pojo.Role;
import com.juzipi.demo.pojo.User;
import com.juzipi.demo.pojo.UserRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.stream.Collectors;


@Service
public class MyUserService implements UserDetailsService {


    //大佬的写法不好学习
    //还是自己重写一遍吧
   /* @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;*/

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)){
            throw new UsernameNotFoundException("用户名不能为空");
        }

//        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        //根据用户名验证用户
        User user = userService.checkUser(username);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

//        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, user.getId()));
        //根据用户id查询出用户角色中间表集合
        List<UserRole> userRoles = userRoleService.queryUserRoleList(user.getId());
//        List<UserRole> userRoles = userRoleRepository.selectList(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, user.getId()));
        if (userRoles != null && !userRoles.isEmpty()){
//            ArrayList<Long> roleIds = new ArrayList<>();
//            for (UserRole list: userRoles){
//                roleIds.add(list.getRoleId());
//            }
            //用stream流的操作把UserRole里的RoleId取出来做了一个集合
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            //根据 用户角色 的id集合获取 角色集合
            List<Role> roles = roleService.queryRoleList(roleIds);
            user.setRoleList(roles);
        }
        return user;
    }


}
